using UnityEngine;

public class TrackSegment : MonoBehaviour
{
    public float segmentLength = 10f; // 此段跑道的长度
    public bool hasObstacle = false; // 是否在这段跑道上生成障碍物
    public GameObject[] obstaclePrefabs; // 可能的障碍物预制件
    
    void Start()
    {
        // 如果设置了生成障碍物，随机决定是否在这段跑道上生成
        if (hasObstacle && obstaclePrefabs.Length > 0 && Random.value > 0.5f)
        {
            SpawnObstacle();
        }
    }
    
    void SpawnObstacle()
    {
        // 随机选择一个障碍物预制件
        int obstacleIndex = Random.Range(0, obstaclePrefabs.Length);
        GameObject obstaclePrefab = obstaclePrefabs[obstacleIndex];
        
        // 随机选择在跑道段上的位置
        float randomZ = Random.Range(0, segmentLength);
        // 限制在跑道宽度范围内
        float randomX = Random.Range(-2f, 2f);
        
        Vector3 spawnPosition = transform.position + new Vector3(randomX, 0.5f, randomZ);
        Instantiate(obstaclePrefab, spawnPosition, Quaternion.identity);
    }
    
    // 用于在编辑器中可视化跑道段的长度
    void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.blue;
        Gizmos.DrawWireCube(
            transform.position + new Vector3(0, 0.1f, segmentLength / 2), 
            new Vector3(6f, 0.2f, segmentLength)
        );
    }
}